﻿using System.Collections.Generic;
using System.Linq.Expressions;

namespace MySql.Simple.Mapper.Linq.ExpressionVisitors
{
    /// <summary>
    /// Transforms <see cref="NewExpression"/> objects into MySQL syntax
    /// </summary>
    public class NewExpressionVisitor : IExpressionVisitor
    {
        /// <summary>
        /// Determines whether this instance can visit the specified expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>
        /// 	<c>true</c> if this instance can visit the specified expression; otherwise, <c>false</c>.
        /// </returns>
        public bool CanVisit(Expression expression)
        {
            return expression is NewExpression;
        }

        /// <summary>
        /// Visits the specified expression and returns a string representation of it's contents.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="query"></param>
        /// <returns></returns>
        public SqlQuery Visit(Expression expression, SqlQuery query)
        {
            var newExpression = (NewExpression)expression;


            var args = new List<object>();

            foreach (var argument in newExpression.Arguments)
            {
                if (argument.NodeType == ExpressionType.MemberAccess)
                {
                    var q = new SqlGenerator().Generate(argument, new SqlQuery());

                    query.Fields += q.Fields;
                }

                else if (argument is ConstantExpression)
                {
                    var ce = (ConstantExpression)argument;

                    args.Add(ce.Value);
                }
            }

            if (args.Count > 0)
            {
                query.Where += newExpression.Constructor.Invoke(args.ToArray());
            }



            return query;
        }
    }
}
